﻿using BaseUtils;
using BaseUtils.AppConfig;
using BaseUtils.Helper;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Button = BaseUtils.AppConfig.Button;

namespace UserManage
{
    public class Authentication
    {

        public static UserInfo CurrentLoginUser { get; set; }
        public static UserConfig Users;
        public static string UserConfigFile = "UserConfig.xml";

        /// <summary>
        /// 是否登录
        ///  true = 已登录
        ///  false = 未登录
        /// </summary>
        /// <returns></returns>
        public static bool IsAuthenticated()
        {
            return CurrentLoginUser != null;
        }

        public void LoadingUserList()
        {
            if (File.Exists(UserConfigFile))
            {
                Users = XmlHelper.Deserialize<UserConfig>(UserConfigFile);
            }
            else
            {
                Users = new UserConfig();
            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="UserCode"></param>
        /// <returns></returns>
        public static UserInfo Login(string UserCode)
        {
            UserInfo userInfo = null;
            if ((UserCode == "x") && File.Exists("debuguser.txt"))
            {
                userInfo = new UserInfo()
                {
                    User = "admin",
                    Level = 5,
                    LevelName = "管理员",
                    UserName = "ADMIN",
                };
            }
            else
            {
                userInfo = Users.List1.Where(u => u.User == UserCode).FirstOrDefault();
            }
            if (userInfo != null && userInfo.Level == 5)
            {
                SetAdmin(userInfo);
            }
            CurrentLoginUser = userInfo;
            return userInfo;
        }

        public static bool Logout()
        {
            CurrentLoginUser = null;
            return true;
        }

        /// <summary>
        /// 管理员
        /// </summary>
        /// <returns></returns>
        private static UserInfo SetAdmin(UserInfo userInfo)
        {
            List<Visit> visits = new List<Visit>();

            foreach (Page item in BaseService.AppConfig.Securitys.Pages)
            {
                Visit visit = new Visit();
                visit.Key = item.Name;
                visit.Names = item.Buttons.Select(b => SingleControlName(item.Name, b.Name)).ToHashSet();
                visits.Add(visit);
            }
            userInfo.Visits = visits;
            return userInfo;
        }

        /// <summary>
        /// 初始化当前页面可访问的权限设置，
        /// </summary>
        /// <param name="form"></param>
        public static void VisibleControl(Form form)
        {
            if (CurrentLoginUser == null)
            {
                return;
            }
            CurrentLoginUser.Visits.ForEach(vi =>
            {
                if (form.Name == vi.Key)
                {
                    BaseService.AppConfig.Securitys.Pages.ForEach(page =>
                    {
                        if (page.Name == vi.Key)
                        {
                            List<string> AllButton = page.Buttons.Select(b => b.Name).ToList();
                            page.Buttons.ForEach(b =>
                            {
                                FindControlByName(form, b, vi.Names, AllButton);
                            });
                        }
                    });
                }
            });
        }

        public static void FindControlByName(Form form, Button name, HashSet<string> Names, List<string> AllButton)
        {
            // 使用 Controls.Find 方法通过名称获取控件  btn权限登录
            if (!string.IsNullOrEmpty(name.Parent))
            {
                Control[] controls = form.Controls.Find(name.Parent, true);
                string ControlName = controls[0].GetType().Name;
                if (controls.Length > 0)
                {
                    MenuStrip(form, Names, controls, ControlName, AllButton);
                }
            }
            else
            {
                Control[] controls = form.Controls.Find(name.Name, true);
                // 如果找到了控件
                if (controls.Length > 0)
                {
                    Control FoundControl = controls[0];
                    FoundControl.Enabled = Names.Contains(SingleControlName(form.Name, name.Name));
                }
            }
        }

        private static void MenuStrip(Form form, HashSet<string> Names, Control[] controls, string ControlName, List<string> AllButton)
        {
            if (ControlName == "MenuStrip")
            {
                MenuStrip menuStrip = (MenuStrip)controls[0];
                List<ToolStripMenuItem> child = new List<ToolStripMenuItem>();
                foreach (ToolStripMenuItem item1 in menuStrip.Items)
                {
                    child.Add(item1);
                }
                DeepFind(form, Names, AllButton, child);
            }
        }

        private static void DeepFind(Form form, HashSet<string> Names, List<string> AllButton, List<ToolStripMenuItem> toolStripMenuItems)
        {
            foreach (ToolStripMenuItem item in toolStripMenuItems)
            {
                if (!AllButton.Contains(item.Name))
                {
                    continue;
                }
                if (item.HasDropDownItems)
                {
                    List<ToolStripMenuItem> child = new List<ToolStripMenuItem>();
                    foreach (ToolStripMenuItem item1 in item.DropDownItems)
                    {
                        child.Add(item1);
                    }
                    DeepFind(form, Names, AllButton, child);
                }

                item.Enabled = Names.Contains(SingleControlName(form.Name, item.Name));
            }
        }

        public static string SingleControlName(string PageName, string ControlName)
        {
            return ControlName;
            //return PageName + "__" + ControlName;
        }
    }
}
